<?php
namespace app\index\service;
use think\Db;
use think\Log;
use sendsms\SmsDemo2;
use sendsms\SmsDemo4;
use app\index\model\Nav;
use app\index\model\Order;
use app\index\model\KnowUserVip;
use wxpay\WxPayApi;
use wxpay\NativePay;
use wxpay\PayNotifyCallBack;
use wxpay\database\WxPayOrderQuery;
use wxpay\database\WxPayUnifiedOrder;
use alipay\pagepay\service\AlipayTradeService;
use alipay\pagepay\buildermodel\AlipayTradePagePayContentBuilder;


class OrderService
{
	public function addOrder($param)
	{
		$user = user();

		if ($param['orderid'])
		{
			$order = Order::getDetail($param['orderid']);

			$orderId = $param['orderid'];
		}
		
		if (!$order)
		{
			$nav = $param['id'] ? Nav::getOneData($param['id']) : [];

			$nav = CourseService::getNavPrice($nav, $param['pack']);

			if (!$nav) return [];

			$orderId = time().rand_num();

			if ($user['id'] == '97caaf5ca038bd9be6b5443cbe046671') $nav['nav_price'] = '0.01';

			$arr = array(
				'title' => $nav['nav_name'],
				'order_id' => $orderId,
				'money' => $nav['nav_price'],
				'user_id' => $user['id'],
				'nav_id' => $param['id'],
				'pack_id' => $param['pack'],
				'action' => $param['action'],
				'created_time' => date('Y-m-d H:i:s'),
				'updated_time' => date('Y-m-d H:i:s'),
			);

			Order::insert($arr);
		}

		return $orderId;
	}

	public function disposeAlipay($config, $order)
	{
		$out_trade_no = $order['order_id'];
		$subject = $body = $order['title'];
		$total_amount = $order['money'];
		$payRequestBuilder = new AlipayTradePagePayContentBuilder();
		$payRequestBuilder->setBody($body);
		$payRequestBuilder->setSubject($subject);
		$payRequestBuilder->setTotalAmount($total_amount);
		$payRequestBuilder->setOutTradeNo($out_trade_no);
		$aop = new AlipayTradeService($config);
		$response = $aop->pagePay($payRequestBuilder,$config['return_url'],$config['notify_url']);
		return $reponse;
	}


	public function alipayNotify($config, $param){
		$alipaySevice = new AlipayTradeService($config);
		$alipaySevice->writeLog('order:'.var_export($param,true));
		$order = Order::getDetail($param['out_trade_no']);
		if (!isset($order)) die($alipaySevice->writeLog('未找到订单，id= ' . $param['out_trade_no']));
		$alipaySevice->writeLog('order:'.var_export($order,true));
		if($order['status'] == 0){
			$alipaySevice->writeLog(var_export($param,true));
			if($param['trade_status'] == 'TRADE_SUCCESS') {
				if($param['receipt_amount'] == $order['money']){
					$data['action'] = 1;
					self::sendMessage($order,$data,'支付宝');
					return 'success';
				}else{
					return 'fail';
				}
			}else {
				return "fail";
			}
		}else{
			return 'success';
		}
	}



	/**
	* 使用微信支付SDK生成支付用的二维码
	* @param $id
	*/
	public function wxpayQRCode($data)
	{
		$order = Order::getDetail($data['order_id']);
		if (!isset($order)) $this->error('查询不到正确的订单信息');
		$interval = date_diff(new \DateTime($order['updated_time']), new \DateTime());
		$h = $interval->format('%h');
		$money = $data['money']*100;
		$notify = new NativePay();
		$input = new WxPayUnifiedOrder();
		$input->setBody('迅达学院-'.$order['title'].'-购买');
		$input->setAttach("test");
		$input->setOutTradeNo($data['order_id']);
		$input->setTotalFee($money);
		$input->setTimeStart(date("YmdHis"));
		$input->setTimeExpire(date("YmdHis", time() + 600));
		$input->setGoodsTag("QRCode");
		$input->setNotifyUrl("https://www.atxunda.com/index/order/wxnotify/id/" . $data['order_id']);
		$input->setTradeType("NATIVE");
		$input->setProductId($data['order_id']);
		$result = $notify->getPayUrl($input);
		$code_url = $result["code_url"];
		return self::getUrlQRCode($code_url);
	}


	/**
	* 异步接收订单返回信息，订单成功付款后，处理订单状态并批量生成用户的二维码
	* @param int $id 订单编号
	*/
	public function wxNotify($param)
	{
		$notify = new PayNotifyCallBack();
		$notify->handle(true);
		//找到匹配签名的订单
		$order = Order::getDetail($param['id']);
		if (!isset($order)) Log::write('未找到订单，id= ' . $param['id']);
		$succeed = ($notify->getReturnCode() == 'SUCCESS') ? true : false;
		if($order['status'] == 0){
			if ($succeed) {
				$data['action'] = 2;
				self::sendMessage($order,$data,'微信');
				if($order['rechargeId']) self::sendMessageMoney($order,$data,'微信');
				Log::write('订单' . $param['id'] . '生成二维码成功');
				Log::write('订单' . $param['id'] . '状态更新成功');
			} else {
				Log::write('订单' . $param['id'] . '支付失败');
			}
		}else{
			Log::write('订单' . $param['id'] . '生成二维码成功');
			Log::write('订单' . $param['id'] . '状态更新成功');
		}
	}

	public static function getUrlQRCode($url)
	{
		return 'https://www.atxunda.com/qrcode.php?data='.$url;
	}

	public function wxReturn($param)
	{
		$input = new WxPayOrderQuery();
		$WxPayApi = new WxPayApi();
		$input->setOutTradeNo($param['id']);
		$trade = WxPayApi::orderQuery($input);
		$order = Order::getDetail($param['id']);
		if($order['status'] == 1){
			return true;
		}else{
			return false;
		}
	}


	public function sendMessage($order,$data,$status){
		$data['status'] = 1;
		$data['updated_time'] = $order['updated_time'] = date('Y-m-d H:i:s');
		$order['orderid'] = $order['id'];
		$order['id'] = $order['user_id'];
		$order['year'] = 2;
		if (!$order['pack_id'] || $order['pack_id'] != 3) KnowUserVip::setUserVip($order, 'index');
		Order::where('order_id',$order['order_id'])->update($data);
		// $users = $order['know_phone'];
		// $instance = new SmsDemo2();
		// $instance->sendSms('18500774590',$users,$status,$order['title'],$order['money']);
		// $instance4 = new SmsDemo4();
		// $instance4->sendSms($users,date('Y年m月d日H时i分s秒',strtotime($order['updated_time'])),$order['title']);
	}
}